package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constant.GlobalConstant;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        //1.检查参数
        //1.1错误-抛异常
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }
        //2.根据用户账户查询用户
        WmUser user = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //2.1用户为空-抛异常
        if(user==null)
        {
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        //3.加盐加密检验密码
        //3.1密码错误-抛异常
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex((dto.getPassword()+user.getSalt()).getBytes())))
        {
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.生成token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        user.setPassword("");
        user.setSalt("");
        Map<String,Object> map=new HashMap<>();
        map.put(GlobalConstant.USER_TAG,user);
        map.put(GlobalConstant.TOKEN_TAG,token);
        //5.返回数据
        return ResponseResult.okResult(map);
    }
}